package leetcode_day._2021._202109._2130;

import general_class.ListNode;

import java.util.Arrays;

/**
 * @author yzh
 * @version 1.0
 * @date 2021/9/22 8:46
 * 分隔链表
 * 算法：链表
 */
public class _22_725 {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        System.out.println(Arrays.toString(new _22_725().splitListToParts(head, 5)));
    }

    public ListNode[] splitListToParts(ListNode head, int k) {
        int num = 0;
        ListNode cur = head;
        while (cur != null) {
            ++num;
            cur = cur.next;
        }
        ListNode[] ans = new ListNode[k];
        for (int i = 0; i < k; i++) {
            int delta = (int) Math.ceil(num * 1.0 / (k - i));
            num -= delta;
            cur = head;
            ans[i] = cur;
            for (int j = 0; j < delta; j++) {
                head = head.next;
                if (j != delta - 1) cur = cur.next;
                if (head == null) break;
            }
            if (head == null) break;
            cur.next = null;
        }
        return ans;
    }

}
